//
//  HCGGoodsDetailViewController.m
//  HappyChildren
//
//  Created by WillyZhao on 2017/5/10.
//  Copyright © 2017年 WillyZhao. All rights reserved.
//

#import "HCGGoodsDetailViewController.h"

#import "HCGoodsListModel.h"

#import "AppDelegate.h"

#import "YBKPPTVC.h"

#import "HCFindGoodsDetailView.h"

#import "HCFindPayView.h"

@interface HCGGoodsDetailViewController () <UIWebViewDelegate> {
    
    CGFloat height_new;
    UIScrollView *scroll;
    HCGoodsListData *data;
    UIView *vc;
    UIView *currentImageV;
    
    //购买视图
    
    YBKPPTVC *pptvc;//banner图
    __weak  UIView *pptView;
    MBProgressHUD *hubddd;
}

@property (nonatomic, strong) HCFindGoodsDetailView *detailView;
@property (nonatomic, strong) HCFindPayView *payView;
//@property (nonatomic, strong) UIWebView *detailWeb;
@property (nonatomic, strong) UIView *maskView;
@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, copy) NSString *titleName;
@property (nonatomic, strong) NSDictionary *addressDic;
@property (nonatomic, strong) NSDictionary *goodData;
@property (nonatomic, copy) NSString *choosedGoodsImage;

@end

@implementation HCGGoodsDetailViewController

- (void)dealloc {
    
    NSLog(@"HCGGoodsDetailViewController dealloc");
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"getaddress" object:nil];
    [vc removeFromSuperview];
}

- (void)viewWillDisappear:(BOOL)animated {

    [super viewWillDisappear:animated];
    vc.hidden = YES;
    [UIView animateWithDuration:0.35f animations:^{
        
        self.payView.frame = CGRectMake(0, Screen_height+15, YBKWinFrame.size.width, YBKAdaptiveH(330));
        self.maskView.hidden = YES;
        self.view.transform =  CGAffineTransformScale(CGAffineTransformIdentity, 1.0, 1.0);
        
    } completion:^(BOOL finished) {
        
    }];
}

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];
    vc.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSLog(@"上个页面传输的数据id:%@",self.parameterObject);
    self.addressDic = [NSDictionary dictionary];
    self.goodData = [NSDictionary dictionary];
    data = (HCGoodsListData *)self.parameterObject;
    self.dataRequest.delegate = self;
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.centerView.frame.size.width, self.centerView.frame.size.height)];
    self.scrollView.backgroundColor = [UIColor whiteColor];
    [self.centerView addSubview:self.scrollView];
    
    vc = [[UIView alloc] initWithFrame:CGRectMake(0, Screen_height-44, Screen_width, 44)];
    [YBKShareAppDelegate.window addSubview:vc];
    
    //添加收藏btn
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.centerView.frame.size.width/2, vc.frame.size.height)];
    btn.tag = 1;
    [btn setTitle:@"我要收藏" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn setBackgroundColor:[UIColor whiteColor]];
    [btn addTarget:self action:@selector(sureBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [vc addSubview:btn];
    //添加兑换btn
    UIButton *btn_sure = [[UIButton alloc] initWithFrame:CGRectMake(btn.frame.size.width, 0, btn.bounds.size.width, btn.bounds.size.height)];
    btn_sure.tag = 2;
    [btn_sure setTitle:@"立即兑换" forState:UIControlStateNormal];
    [btn_sure setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn_sure setBackgroundColor:YBKRGBCOLOR(240, 96, 96, 1)];
    [btn_sure addTarget:self action:@selector(sureBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [vc addSubview:btn_sure];
    btn_sure.titleLabel.font = [UIFont systemFontOfSize:16];
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_width, 0.5)];
    line.backgroundColor = [UIColor lightGrayColor];
    [vc addSubview:line];

    //原生动效
    self.payView = [[HCFindPayView alloc] initWithFrame:CGRectMake(0, Screen_height+15, YBKWinFrame.size.width, YBKAdaptiveH(330))];
    self.payView.backgroundColor = [UIColor whiteColor];
    [YBKShareAppDelegate.window addSubview:self.payView];
    
    //遮罩层
    self.maskView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.maskView setBackgroundColor:[UIColor blackColor]];
    [self.maskView setAlpha:0];
    UITapGestureRecognizer *reAnGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(reAnGRAction)];
    [self.maskView addGestureRecognizer:reAnGR];
    
    CGRect frame = [self initBannerPic];
    self.detailView = [[HCFindGoodsDetailView alloc] initWithFrame:CGRectMake(0, frame.size.height, Screen_width, 212)];
    self.detailView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:self.detailView];
    
    __weak typeof (self)weakSelf = self;
    [weakSelf.detailView setDidClickAddressViewBlock:^{
       
        //点击地址
        [weakSelf pushChildrenViewController:@"HCAddressManagerController" parameterObject:nil dataObject:nil];
    }];
    
    [weakSelf.detailView setDidClickCollectButtonBlock:^{
       
        //点击收藏
        //我要收藏
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定收藏此商品" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf.dataRequest post_HCGoodsCollect:weakSelf.parameterObject user:HCGETUSER(@"userid")];
        }]];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }]];
        
        [weakSelf presentViewController:alert animated:YES completion:NULL];
    }];
    
    [weakSelf.payView setSureButtonClick:^(NSString *color, NSString *size, NSString *sum){
       
        //点击选购
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        if (![PublicFunction isNull:color]) {
            
            [dic setObject:color forKey:@"color"];
        }
        if (![PublicFunction isNull:size]) {
            
            [dic setObject:size forKey:@"size"];
        }
        if (![PublicFunction isNull:sum]) {
            
            [dic setObject:sum forKey:@"sum"];
        }
        [dic setObject:weakSelf.titleName forKey:@"name"];
        [dic setObject:[weakSelf.goodData objectForKey:@"freight"] forKey:@"freight"];
        [dic setObject:[weakSelf.goodData objectForKey:@"price"] forKey:@"price"];
        [dic setObject:weakSelf.parameterObject forKey:@"qid"];
        [dic setObject:weakSelf.choosedGoodsImage forKey:@"image"];
        if (weakSelf.addressDic.count != 0) {
            NSLog(@"dasdasdasd----%@",weakSelf.addressDic);
            [dic setObject:[weakSelf.addressDic objectForKey:@"address"] forKey:@"address"];
            [dic setObject:[weakSelf.addressDic objectForKey:@"id"] forKey:@"id"];
            [dic setObject:[weakSelf.addressDic objectForKey:@"name"] forKey:@"recipient"];
            [dic setObject:[weakSelf.addressDic objectForKey:@"phone"] forKey:@"phone"];
        }
        
        [UIView animateWithDuration:0.35f animations:^{
            
            weakSelf.maskView.hidden = YES;
            weakSelf.payView.frame = CGRectMake(0, Screen_height+15, Screen_width, YBKAdaptiveH(330));
            weakSelf.scrollView.transform =  CGAffineTransformScale(CGAffineTransformIdentity, 1.0, 1.0);
            weakSelf.view.transform =  CGAffineTransformScale(CGAffineTransformIdentity, 1.0, 1.0);
            
        } completion:^(BOOL finished) {
            
            [weakSelf pushChildrenViewController:@"HCBuyGoodsController" parameterObject:dic dataObject:nil];
        }];
    }];
    
    self.scrollView.contentSize = CGSizeMake(self.centerView.frame.size.width, Screen_height);
    [self.view addSubview:self.maskView];
    self.maskView.hidden = YES;
    
    //获取数据
    self.dataRequest.delegate = self;
    [self.dataRequest post_HCGoodsDetailWithID:self.parameterObject];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getCurrentAddress:) name:@"getaddress" object:nil];
}

- (void)getCurrentAddress:(NSNotification *)obj {

    NSDictionary *dic = [obj userInfo];
    NSDictionary *addressDic = [dic objectForKey:@"address"];
    self.addressDic = [NSDictionary dictionaryWithDictionary:addressDic];
    self.detailView.addressData = addressDic;
}

#pragma mark 初始化banner图片
-(CGRect)initBannerPic {
    
    pptvc = [[YBKPPTVC alloc] init];
    __weak YBKPPTVC *p= pptvc;
    pptvc.clickBlock = ^(HCHomeBannerModel *model) {
        NSLog(@"点击了");
    };
    
    pptvc.scrollBlock = ^(NSInteger m) {

        p.pptPageControl.currentPage = m;
    };
    
    //这里-20是一个bug
    pptvc.view.frame=CGRectMake(0, 0,self.centerView.bounds.size.width, YBKAdaptiveH(294));
    pptView=pptvc.view;
    pptvc.view.backgroundColor = [UIColor lightGrayColor];
    [self addChildViewController:pptvc];
    [pptvc didMoveToParentViewController:self];
    [self.scrollView addSubview:pptvc.view];
    return pptvc.view.frame;
}

- (void)reAnGRAction
{
    [UIView animateWithDuration:0.35f animations:^{
        
        self.payView.frame = CGRectMake(0, Screen_height+15, YBKWinFrame.size.width, YBKAdaptiveH(330));
        self.maskView.hidden = YES;
        self.view.transform =  CGAffineTransformScale(CGAffineTransformIdentity, 1.0, 1.0);

    } completion:^(BOOL finished) {
        
    }];
}

-(void)sureBtnAction:(UIButton *)btn {

    //我要兑换
    if (btn.tag == 2) {

        [UIView animateWithDuration:0.35f animations:^{
            
            self.maskView.hidden = NO;
            [self.maskView setAlpha:0.5f];
            self.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.92, 0.92);
        } completion:^(BOOL finished) {
        }];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [UIView animateWithDuration:0.35f animations:^{

                self.payView.frame = CGRectMake(0, Screen_height-YBKAdaptiveH(330), Screen_width, YBKAdaptiveH(330));
                
            } completion:^(BOOL finished) {
                
            }];
        });
        
    }else {
        
        //我要收藏
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定收藏此商品" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.dataRequest post_HCGoodsCollect:self.parameterObject user:HCGETUSER(@"userid")];
        }]];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }]];
        
        [self presentViewController:alert animated:YES completion:NULL];
    }
}
#pragma mark 图片压缩
-(UIImage *)imageWithImage:(UIImage*)image
               scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
    
}

#pragma mark 网络请求回调
-(void)dataRequesterFinish:(DataRequester *)requester requesterWithType:(DataRequestType)aType receiveDictionary:(NSDictionary *)dictionary {
    
    if (aType == HC_HOMEGOODSIMAGE_TYPE) {
        NSLog(@"商品图片信息:%@",dictionary);
        
        NSMutableArray *images = [NSMutableArray arrayWithArray:dictionary[@"img"]];
        NSMutableArray *arr = [NSMutableArray array];
        
        for (int i = 0; i<images.count; i++) {
            
            if ([[SDWebImageManager sharedManager] cachedImageExistsForURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",images[i][@"pic"]]]]) {
                //存在
                UIImage *image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:[NSString stringWithFormat:@"%@",images[i][@"pic"]]];
                if (arr.count>0) {
                    UIView *vc1 = (UIView *)arr[arr.count - 1];
                    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
                    imageView.frame = CGRectMake(0, CGRectGetMaxY(vc1.frame), self.centerView.frame.size.width, image.size.height);
                    [self.scrollView addSubview:imageView];
                    self.scrollView.contentSize = CGSizeMake(self.centerView.frame.size.width, imageView.frame.origin.y+imageView.frame.size.height+44);
                    [arr addObject:imageView];
                }else{
                    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
                    imageView.frame = CGRectMake(0, CGRectGetMaxY(self.detailView.frame), self.centerView.frame.size.width, image.size.height);
                    [self.scrollView addSubview:imageView];
                    self.scrollView.contentSize = CGSizeMake(self.centerView.frame.size.width, imageView.frame.origin.y+imageView.frame.size.height+44);
                    [arr addObject:imageView];
                }
            }else{
                [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",images[i][@"pic"]]] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                    
                } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
                    
                    //压缩图片
//                    CGFloat w = image.size.width/2.0;
                    CGFloat h = image.size.height * 0.47;
                    image = [self imageWithImage:image scaledToSize:CGSizeMake(self.centerView.frame.size.width, h)];
                    
                    if (arr.count>0) {
                        UIView *vc1 = (UIView *)arr[arr.count - 1];
                        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
                        imageView.frame = CGRectMake(0, CGRectGetMaxY(vc1.frame), self.centerView.frame.size.width, image.size.height);
                        [self.scrollView addSubview:imageView];
                        self.scrollView.contentSize = CGSizeMake(self.centerView.frame.size.width, imageView.frame.origin.y+imageView.frame.size.height+44);
                        [arr addObject:imageView];
                        
                    }else{
                        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
                        imageView.frame = CGRectMake(0, CGRectGetMaxY(self.detailView.frame), self.centerView.frame.size.width, image.size.height);
                        [self.scrollView addSubview:imageView];
                        self.scrollView.contentSize = CGSizeMake(self.centerView.frame.size.width, imageView.frame.origin.y+imageView.frame.size.height+44);
                        [arr addObject:imageView];
                    }
                    if (finished) {
                        [[SDWebImageManager sharedManager] saveImageToCache:image forURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",images[i][@"pic"]]]];
                    }
                }];
            }
            
            
        }
        
        //添加提示图片
        
        if (arr.count == images.count) {
            UIImage *im = [UIImage imageNamed:@"哈哈"];
            UIImageView *imageaa  = [[UIImageView alloc] initWithImage:im];
            UIView *vv = (UIView *)arr[arr.count - 1];
            imageaa.frame = CGRectMake(0, vv.frame.origin.y+vv.frame.size.height, self.centerView.frame.size.width, im.size.height);
            [self.scrollView addSubview:imageaa];
            self.scrollView.contentSize = CGSizeMake(self.centerView.frame.size.width, imageaa.frame.origin.y+imageaa.frame.size.height+44);
        }
        
        //获取缓存的大小
        //在获取缓存的方法写上这两句代码
        NSUInteger intg = [[SDImageCache sharedImageCache] getSize];
        //
        NSString * currentVolum = [NSString stringWithFormat:@"%@",[self fileSizeWithInterge:intg]];
        NSLog(@"缓存大小:%@",currentVolum);
        return;
    }
    
    if (aType == HC_GOODSDETAIL_TYPE) {
        
        if (dictionary.count > 0) {
            
            self.goodData = dictionary;
            if ([dictionary[@"img"] isKindOfClass:[NSArray class]]) {
                
                NSArray *arr = [dictionary objectForKey:@"img"];
                pptvc.showModelArray = arr;
                self.payView.goodsImage = arr[0];
                self.choosedGoodsImage = arr[0];
            }
            if ([dictionary[@"img"] isKindOfClass:[NSString class]]) {
                
                NSArray *arr = [NSArray arrayWithObjects:[dictionary objectForKey:@"img"], nil];
                pptvc.showModelArray = arr;
                self.payView.goodsImage = arr[0];
                self.choosedGoodsImage = arr[0];
            }
            
            self.detailView.dataDic = dictionary;
            NSArray *types = [dictionary objectForKey:@"type"];
            if (types.count > 0) {
                
                self.payView.typeArray = types;
            }
            
            self.textTitle = [NSString stringWithFormat:@"%@",[dictionary objectForKey:@"name"]];
            self.titleName = [NSString stringWithFormat:@"%@",[dictionary objectForKey:@"name"]];
        }
        
        self.payView.goodprice = [NSString stringWithFormat:@"积分:%@",dictionary[@"price"]];
        self.payView.titlename = [NSString stringWithFormat:@"%@",dictionary[@"name"]];
        
        //获取地址信息
        [self.dataRequest post_HCMineAddressList:HCGETUSER(@"userid")];
    }
    else if (aType == HC_GOODSCOLLECT_TYPE){
        
        NSLog(@"收藏网络请求成功:%@",dictionary);
        if ([dictionary[@"stat"] integerValue] == 200) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"收藏成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //TODO
                [self pushChildrenViewController:@"HCMineCollectViewController" parameterObject:nil dataObject:nil];
            }]];
            
            [self presentViewController:alert animated:YES completion:NULL];
        }else{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"收藏失败" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //TODO
            }]];
            
            [self presentViewController:alert animated:YES completion:NULL];
        }
    }
    else {
        [self.dataRequest post_HCGoodsImage:self.parameterObject];
        //获取地址信息成功
        if (dictionary) {
            
            NSArray *arr = [dictionary objectForKey:@"address"];
            if (arr.count > 0) {
                
                for (int i = 0; i < arr.count; i++) {
                    
                    NSString *state = [arr[i] objectForKey:@"stat"];
                    if ([state integerValue] == 1) {
                        
                        self.detailView.addressData = arr[i];
                        self.addressDic = arr[i];
                    }
                }
            }
        }
    }
}

//计算出大小
- (NSString *)fileSizeWithInterge:(NSInteger)size{
    // 1k = 1024, 1m = 1024k
    if (size < 1024) {// 小于1k
        return [NSString stringWithFormat:@"%ldB",(long)size];
    }else if (size < 1024 * 1024){// 小于1m
        CGFloat aFloat = size/1024;
        return [NSString stringWithFormat:@"%.0fK",aFloat];
    }else if (size < 1024 * 1024 * 1024){// 小于1G
        CGFloat aFloat = size/(1024 * 1024);
        return [NSString stringWithFormat:@"%.1fM",aFloat];
    }else{
        CGFloat aFloat = size/(1024*1024*1024);
        return [NSString stringWithFormat:@"%.1fG",aFloat];
    }
}

-(void)dataRequesterFail:(DataRequester *)requester requesterWithType:(DataRequestType)aType receiveErrorDictionary:(NSDictionary *)dictionary {
    
    NSLog(@"网络请求失败");
    [XHToast showBottomWithText:@"请尝试登录或检查网络条件"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
